<script lang="ts" setup>
import { QForm, type FormItemRows } from '@meetjs/element-plus-kit'
import { type FormRules, ElMessage } from 'element-plus'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { addNotice, updateNotice, getNotice } from '@/api/system/notice'
import type { NoticeParams, NoticeList } from '@/api/system/notice/type'
import Editor from '@/components/Editor/index.vue'

const emits = defineEmits<{
	refresh: []
}>()

const visible = ref(false)
const loading = ref(false)
const initLoading = ref(false)
const title = ref<'新增公告' | '编辑公告'>('新增公告')
const type = ref<'add' | 'edit'>('add')
const formRef = ref()
const baseFormData: NoticeParams = {
	noticeTitle: '',
	noticeType: '',
	status: 0,
	noticeContent: ''
}
const dialogFormValue = ref<NoticeParams>({ ...baseFormData })

const sysNoticeType = ref<IGetDictsRes>([])
const sysNoticeStatus = ref<IGetDictsRes>([])

const dialogOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '公告标题',
		prop: 'noticeTitle',
		col: 12,
		attrs: {
			placeholder: '请输入公告标题',
			clearable: true
		}
	},
	{
		type: 'select',
		label: '公告类型',
		prop: 'noticeType',
		col: 12,
		options: sysNoticeType as unknown as any,
		attrs: {
			placeholder: '请选择公告类型',
			clearable: true
		}
	},
	{
		type: 'radio',
		label: '状态',
		prop: 'status',
		col: 24,
		options: sysNoticeStatus as unknown as any
	}
])

const rules = reactive<FormRules<{ [k: string]: any }>>({
	noticeTitle: [
		{
			required: true,
			message: '请输入公告标题'
		}
	],
	noticeType: [
		{
			required: true,
			message: '请选择公告类型'
		}
	]
})

const init = async (operationType: 'add' | 'edit', editForm?: NoticeList) => {
	visible.value = true
	type.value = operationType
	title.value = operationType === 'add' ? '新增公告' : '编辑公告'

	// 根据操作类型初始化表单数据
	if (operationType === 'edit' && editForm) {
		initLoading.value = true
		try {
			// 编辑模式需要获取详细信息（包含内容）
			if (editForm.id) {
				const { data } = await getNotice(editForm.id)
				dialogFormValue.value = {
					id: data.id,
					noticeTitle: data.noticeTitle,
					noticeType: data.noticeType,
					status: data.status,
					noticeContent: data.noticeContent || ''
				}
			} else {
				// fallback 如果没有ID，使用传入的数据
				dialogFormValue.value = {
					id: editForm.id,
					noticeTitle: editForm.noticeTitle,
					noticeType: editForm.noticeType,
					status: editForm.status,
					noticeContent: editForm.noticeContent || ''
				}
			}
		} catch (error) {
			console.error('获取公告信息失败:', error)
			ElMessage.error('获取公告信息失败，请重试')
		} finally {
			initLoading.value = false
		}
	} else {
		// 新增模式：使用默认数据
		dialogFormValue.value = { ...baseFormData }
	}

	// 清理表单验证状态
	setTimeout(() => {
		formRef.value?.clearValidate()
	})
}

const submit = () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			loading.value = true
			try {
				const apiFunc = type.value === 'add' ? addNotice : updateNotice
				await apiFunc({ ...dialogFormValue.value })
				const message = type.value === 'add' ? '新增成功' : '修改成功'
				ElMessage.success(message)
				visible.value = false
				emits('refresh')
			} catch (error) {
				console.error('操作失败:', error)
				ElMessage.error('操作失败，请重试')
			} finally {
				loading.value = false
			}
		}
	})
}

const getMethods = () => {
	getDicts('sys_sys_notice_type').then(data => {
		sysNoticeType.value = data
	})
	getDicts('sys_sys_notice_status').then(data => {
		sysNoticeStatus.value = data
	})
}

onMounted(() => {
	getMethods()
})

defineExpose({
	init
})
</script>

<template>
	<ElDialog
		v-model="visible"
		:title="title"
		:close-on-click-modal="false"
		:close-on-press-escape="false"
		width="800px"
	>
		<div
			v-loading="initLoading"
			element-loading-text="正在加载数据..."
			style="min-height: 400px"
		>
			<QForm
				v-if="!initLoading"
				ref="formRef"
				label-width="80px"
				:model="dialogFormValue"
				:form-options="dialogOptions"
				:rules="rules"
				:required="true"
				:gutter="20"
			/>
			<div
				v-if="!initLoading"
				class="mt-4"
			>
				<el-form-item
					label="内容"
					label-width="80px"
					label-position="right"
				>
					<Editor
						v-model="dialogFormValue.noticeContent"
						:min-height="192"
					/>
				</el-form-item>
			</div>
		</div>
		<template #footer>
			<el-button
				:disabled="loading"
				@click="visible = false"
			>
				取消
			</el-button>
			<el-button
				type="primary"
				:loading="loading"
				:disabled="initLoading"
				@click="submit"
			>
				确定
			</el-button>
		</template>
	</ElDialog>
</template>

<style lang="scss" scoped></style>
